<?php
/**
 * 基类
 */
class base{
	//samrty
	private $smarty = null;
	//db
	private $db = null;
	// log 
	protected $log = null;
	
	/**
	 * 构造函数
	 */
	public function __construct(){
		$this->isUserLogin();
		//smarty实例化
		$this->smarty = System::load_sys_class('subsmarty');
		$this->log = System::load_sys_class('logutil');
		//images_url
		$this->smarty->assign('IMG_URL', IMAGES_URL);
		$this->smarty->assign('JS_URL', JS_URL);
		$this->smarty->assign('CSS_URL', CSS_URL);
		$this->smarty->assign('BASE_URL', BASE_URL);
		$this->smarty->assign('WEB_URL', WEB_URL);
	}
	
	/**
	 * 析构函数
	 */
	public function __destruct(){
		if($this->db != null){
			$this->db->close();
		}
	}
	
	/**
	 * 如果数据库连接为空则初始化
	 */
	private function initDB(){
		if($this->db == null){
			System::load_sys_class('dbutil','sys',false);
			$this->db = new dbutil();
		}
	}
	
	/**
	 * 获取当前用户id
	 */
	protected function getUid(){
		return _encrypt(_getcookie("uid"),'DECODE');
	}
	
	/**
	 * 往$table表中插入一条$record
	 */
	protected function saveRecord($table,$record,$getSql=false){
    	if(empty($table))
    		return false;
    	if(!is_array($record) || empty($record))
    		return false;
    	$this->initDB();
    	$r = array();
    	foreach($record as $key=>$item){
    		$r[$this->db->escape($key)] = $this->db->escape($item);
    	}
    	$cols = implode("," , array_keys($r));
    	$values = implode("','" , $r);
    	$sql = "insert into " . $this->db->escape($table) . " (" . $cols . ") values ('" . $values . "')";
    	if($getSql){
    		return $sql;
    	}else{
    		return $this->db->query($sql) ? $this->db->getlastid() : false;
    	}
    }
    
    /**
     * 根据id修改$table中的记录
     */
    protected function updateById($table,$record,$id,$idkey="id",$getSql=false){
    	if(empty($table) || empty($id) || empty($idkey))
    		return false;
    	if(!is_array($record) || empty($record))
    		return false;
    	$this->initDB();
    	$arr = array();
    	foreach($record as $key=>$item){
    		$arr[] = $this->db->escape($key) . " = '" . $this->db->escape($item) . "' ";
    	}
    	$sets = implode("," , $arr);
    	$sql = "update " . $this->db->escape($table) . " set " . $sets . " where ".$this->db->escape($idkey)." = '" . $this->db->escape($id) . "'";
    	if($getSql){
    		return $sql;
    	}else{
    		return $this->db->query($sql);
    	}
    }
    
    /**
	 * 根据id查询数据
	 */
    protected function getById($table,$id,$idkey="id"){
    	if(empty($table) || empty($id) || empty($idkey))
    		return false;
    	$this->initDB();
    	$sql = "select * from $table where ".$this->db->escape($idkey)." = '$id'";
    	$result = $this->db->getOneRow($sql);
    	return $result;
    }
    
    /**
	 * 根据id删除数据
	 */
    protected function delById($table,$id,$idkey="id",$getSql=false){
    	if(empty($table) || empty($id) || empty($idkey))
    		return false;
    	$this->initDB();
    	$sql = "delete from $table where ".$this->db->escape($idkey)." = '$id'";
    	if($getSql){
    		return $sql;
    	}else{
    		return $this->db->query($sql);
    	}
    }
    
    /**
     * 查一条数据
     */
    protected function getOneRow($sql){
    	if(empty($sql)){
    		return false;
    	}
    	$this->initDB();
    	return $this->db->getOneRow($sql);
    }
    
    /**
     * 查全部数据
     */
    protected function getAll($sql){
    	if(empty($sql)){
    		return false;
    	}
    	$this->initDB();
    	return $this->db->getAll($sql);
    }
    
    /**
     * 使用事物执行sql
     */
    protected function execute($sqlArr){
    	if(!is_array($sqlArr) || empty($sqlArr))
    		return false;
    	$this->initDB();
    	$this->db->autoCommit(false);
    	$this->db->start();
    	foreach($sqlArr as $sql){
    		if(!$this->db->query($sql)){
    			$this->db->rollback();
    			$this->db->autoCommit(true);
    			return false;
    		}
    	}
    	$this->db->commit();
    	$this->db->autoCommit(true);
    	return true;
    }
    
    /**
     *  防注入
     */
    protected function escape($value){
    	$this->initDB();
    	return $this->db->escape($value);
    }
	
	/**
	 * 给页面传值
	 */
	protected function assign($name,$value){
		$this->smarty->assign($name, $value);
	}
	
	/**
	 * 显示页面
	 */
	protected function display($tpl){
		$this->smarty->display($tpl);
	}
	
	/**
	 * 输出返回内容
	 */
	protected function output($obj){
		if(is_array($obj)){
			echo json_encode($obj,JSON_UNESCAPED_UNICODE);
			exit;
		}else{
			echo $obj;
			exit;
		}
	}
	
	/**
	 * 验证码是否正确
	 */
	protected function checkPhoneAndCode($phone,$code){
		try{
			// 手机或验证码为空
			if(empty($phone) || empty($code)){
				return false;
			}
            $phone = strtoupper(sha1(trim($phone)));
            $code = strtoupper(sha1(trim($code)));
            $sql = "select * from phone_code where phone = '".$this->escape($phone)."'";
            $res = $this->getOneRow($sql);
            // 没有查询结果
            if(empty($res)){
                return false;
            }
            if($res['code'] !== $code){
                return false;
            }
            // 获得当前时间
            $c_time = time();
            // 判断验证码是否过期
            if($res['expire_time'] < $c_time){
                return false;
            }
            return true;
        }catch (Exception $e){
            return false;
        }
	}
	
	/**
	 * 用户是否登录
	 */
	private function isUserLogin(){
	 	$uid=_encrypt(_getcookie("uid"),'DECODE');
		if($uid == ""){
			$appid = APP_ID;
			$secret = SECRET;
			$m = empty($_GET['module']) ? ROUTE_M : $_GET['module'];
			$c = empty($_GET['controller']) ? ROUTE_C : $_GET['controller'];
			$a = empty($_GET['action']) ? ROUTE_A : $_GET['action'];
			if(($m=='regist' && $c == 'regist') || ($m == "pay" && $c == "wxpay" && $a == "notify")){
				return true;
			}
			$state = $m.'/'.$c.'/'.$a.'/';
			if(!empty($_GET)){
				foreach($_GET as $key=>$item){
					if($key != "module" && $key != "controller" && $key != "action"){
						$state .= $key.'='.$item;
						break;
					}
				}
			}
			$conde = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid . "&redirect_uri=".WEB_URL."regist/regist&response_type=code&scope=snsapi_userinfo&state=$state#wechat_redirect";
			header("Location:" . $conde);
			exit;
		}
	}
}
?>